<template>
  <a-modal
    :title="title"
    :width="720"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          style="margin-bottom: 5px;"
          label="商城名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <span style="margin-left: 23px; color: rgba(0, 0, 0, 0.85);">{{ record.store_name }}</span>
        </a-form-item>
        <a-form-item
          label="模块列表"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          extra="设置当前商城可使用的功能模块"
        >
          <a-tree
            ref="ModuleTree"
            v-model="checkedKeys"
            checkable
            checkStrictly
            :treeData="treeData"
            :autoExpandParent="false"
            @check="onCheckedModule"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import _ from 'lodash'
import * as Api from '@/api/store/module'

export default {
  props: {},
  data () {
    return {
      // 对话框标题
      title: '设置功能模块',
      // 标签布局属性
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      // 输入框布局属性
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      // modal(对话框)是否可见
      visible: false,
      // modal(对话框)确定按钮 loading
      confirmLoading: false,
      // 当前表单
      form: this.$form.createForm(this),
      // 商家记录
      record: {},
      // 系统默认的功能模块
      default: {},
      // 商家分配的功能模块内容
      moduleKeys: {},
      // 功能模块列表 (树状结构)
      treeData: [],
      // 当前选中的keys
      checkedKeys: {
        checked: [],
        halfChecked: []
      }
    }
  },

  created () {
    // 获取系统默认的功能模块
    this.getDefault()
  },

  methods: {

    // 显示模态窗口
    async show (record) {
      // 显示窗口
      this.visible = true
      // 当前商城记录
      this.record = record
      // 获取当前商家的功能模块
      await this.getModuleDetail(record)
      // 格式化Tree数据
      this.getTreeData()
      // 设置默认选中的菜单
      this.setModuleChecked()
    },

    // 格式化Tree数据
    getTreeData () {
      this.treeData = this.formatTreeData(this.default)
    },

    // 获取系统默认的功能模块
    async getDefault () {
      this.confirmLoading = true
      this.default = await Api.getDefault().then(result => result.data.default)
      this.confirmLoading = false
    },

    // 设置默认选中的节点
    setModuleChecked () {
      // 树状结构所有子集
      const { treeData, moduleKeys } = this
      const allKeys = this.getAllKeys(treeData)
      // 默认选中的菜单
      this.checkedKeys.checked = _.intersection(moduleKeys, allKeys)
    },

    // 获取当前商家的功能模块
    async getModuleDetail (record) {
      this.confirmLoading = true
      this.moduleKeys = await Api.detail({ storeId: record['store_id'] }).then(result => result.data.moduleKeys)
      this.confirmLoading = false
    },

    // 格式化权限列表
    formatTreeData (values, parentKey) {
      const data = []
      for (const index in values) {
        const item = values[index]
        // 新的元素
        const newItem = { title: item.name, key: item.key, checkable: !item.required, parentKey }
        // 递归整理子集
        if (item.children) {
          newItem['children'] = this.formatTreeData(item['children'], item.key)
        }
        data.push(newItem)
      }
      return data
    },

    // 确认按钮
    handleSubmit () {
      // 获取所有选中的节点
      const Tree = this.$refs.ModuleTree
      const values = {
        moduleKeys: [
          ...Tree.getCheckedKeys(),
          ...Tree.getHalfCheckedKeys()
        ]
      }
      // 提交到后端api
      this.onFormSubmit(values)
    },

    /**
     * 取消按钮
     */
    handleCancel () {
      this.visible = false
      this.form.resetFields()
      const Tree = this.$refs.ModuleTree
      Tree.clearExpandedKeys()
      this.checkedKeys.checked = []
    },

    /**
    * 提交到后端api
    */
    onFormSubmit (values) {
      this.confirmLoading = true
      // 数据提交
      Api.edit({ storeId: this.record['store_id'], form: values })
        .then(result => {
          // 显示成功
          this.$message.success(result.message)
          // 关闭对话框
          this.handleCancel()
          // 通知父端组件提交完成了
          this.$emit('handleSubmit', values)
        })
        .finally(() => this.confirmLoading = false)
    },


    // 节点选中事件
    onCheckedModule (checkedKeys, { checked, node }) {
      // 寻找当前选择的节点
      const { treeData } = this
      const nodeData = this.findNode(node.eventKey, treeData)
      // 选择节点时联动所有子节点
      this.onCheckChilds(checked, nodeData)
      // 选择节点时联动所有父节点
      this.onCheckParents(checked, nodeData)
    },

    // 寻找指定的的节点
    findNode (key, list) {
      for (let index = 0; index < list.length; index++) {
        const item = list[index]
        if (item.key === key) {
          return item
        } else if (item.children) {
          const result = this.findNode(key, item.children)
          if (result) {
            return result
          }
        }
      }
      return false
    },

    // 选择节点时联动所有父节点
    onCheckParents (checked, node) {
      // 查找所有父节点(方法)
      const { treeData } = this
      const findParentKeys = parentKey => {
        let keys = []
        const parent = this.findNode(parentKey, treeData)
        if (!parent) {
          return keys
        }
        keys.push(parent.key)
        if (parent.children) {
          const arr = findParentKeys(parent.parentKey)
          arr.length && (keys = keys.concat(arr))
        }
        return keys
      }
      // 查找所有父节点
      const parentKeys = findParentKeys(node.parentKey)
      // 设置为选中
      if (checked && parentKeys.length) {
        this.checkedKeys.checked = _.union(this.checkedKeys.checked, parentKeys)
      }
    },

    // 选择节点时联动所有子节点
    onCheckChilds (checked, node) {
      // 获取当前节点的所有子级ID
      const childKeys = node.children ? this.getAllKeys(node.children) : []
      if (childKeys.length) {
        this.checkedKeys.checked = checked ? _.union(this.checkedKeys.checked, childKeys) : _.difference(this.checkedKeys.checked, childKeys)
      }
    },

    // 获取树状结构中所有子级的ID集
    getAllKeys (list) {
      let keysArr = []
      list.forEach(item => {
        keysArr.push(item.key)
        if (item.children && item.children.length) {
          const childrenArr = this.getAllKeys(item.children)
          childrenArr.length && (keysArr = keysArr.concat(childrenArr))
        }
      })
      return keysArr
    },

  }
}
</script>

<style lang="less" scoped>
/deep/.ant-tree-title {
  color: rgba(0, 0, 0, 0.65) !important;
}
</style>
